/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.mail.config;

import org.noear.solon.annotation.*;
import org.simplejavamail.api.email.Email;
import org.simplejavamail.api.mailer.Mailer;
import org.simplejavamail.api.mailer.config.TransportStrategy;
import org.simplejavamail.email.EmailBuilder;
import org.simplejavamail.mailer.MailerBuilder;

/**
 * <b>(MailConfiguration)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/1/18
 */
@Component
@Configuration
@Import(scanPackages = {"info.peigen.hotpot.component.mail", "info.peigen.hotpot.common",
        "com.gitee.peigenlpy.actable", "org.apache.ibatis"})
public class MailConfiguration {
    @Inject
    private MailSenderProperties  mailSenderProperties;
    @Inject
    private MailMessageProperties mailMessageProperties;

    @Bean
    public Mailer initMailer() {
        return MailerBuilder
                .withSMTPServer(mailSenderProperties.getHost(), mailSenderProperties.getPort(),
                        mailSenderProperties.getUsername(), mailSenderProperties.getPassword())
                .withTransportStrategy(TransportStrategy.SMTPS)
                .withSessionTimeout(mailSenderProperties.getSessionTimeout())
                .clearEmailValidator()
                // .withEmailValidator(
                //         JMail.strictValidator()
                //                 .requireOnlyTopLevelDomains(TopLevelDomain.DOT_COM)
                //                 .withRule(email -> email.localPart().startsWith("allowed")))
                .withDebugLogging(mailSenderProperties.isDebug())
                // .async()
                .buildMailer();
    }

    @Bean
    public Email initEmail() {
        return EmailBuilder.startingBlank()
                .from(mailMessageProperties.getFrom())
                .withReplyTo(mailMessageProperties.getFrom())
                .withSubject(mailMessageProperties.getSubject())
                .buildEmail();
    }
}